<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\prepay\gateway;

use app\common\manager\UserAccountManager;
use app\common\model\Config;
use app\common\model\Withdrawrecord;
use think\Db;
use think\Exception;

class Withdraw
{
    CONST METHOD = 'Withdraw';

    CONST TYPE_ALIPAY = 1;
    CONST TYPE_WECHAT = 2;
    public function order($user,$request,$trans=true)
    {
        if ($trans)
            Db::startTrans();
        try {
            $type = $request['type'] ?? 'wechat';
            $singleWithdrawLimit = Config::where('name','single_withdraw_amount_limit')->value('value');
            $singleDayLimit = Config::where('name','single_day_withdraw_limit')->value('value');
            $single_withdraw_min = Config::where('name','single_withdraw_min')->value('value');
            if ($request['amount'] < $single_withdraw_min){
                throw new Exception('单笔最小金额为:'.$single_withdraw_min);
            }

            if ($request['amount'] > $singleWithdrawLimit){
                throw new Exception('单笔最大金额为:'.$singleWithdrawLimit);
            }
            $todayStartTime = strtotime(date('Y-m-d H:i:s',time()));
            $todayEndTime = strtotime(date('Y-m-d 23:59:59',time()));
            $todayAmount = Withdrawrecord::where('user_id',$user->id)->where('create_time','between time',[$todayStartTime,$todayEndTime])->where('status','<>',Withdrawrecord::STATUS_BACK)->sum('amount');

            if (bcadd($todayAmount,$request['amount'],2) > $singleDayLimit){
                throw new Exception('已超过今日限额:'.$singleDayLimit);
            }
            $orderId = orderNum();
            $withdrawOrder = [
                'order'=>$orderId,
                'user_id'=>$user->id,
                'type'=>$type,
                'amount'=>$request['amount'],
                'create_time'=>time()
            ];

            $withdrawOrderInfo = Withdrawrecord::create($withdrawOrder);
            if (!$withdrawOrderInfo){
                throw new Exception('提现订单创建失败');
            }

            $result = UserAccountManager::money($user->id,$request['amount'],UserAccountManager::CHANGE_TYPE_PAYMENT,time(),UserAccountManager::TYPE_FREEZE,['relation_id'=>$withdrawOrderInfo->id,'relation_order'=>$orderId]);
            if ($result['code'] != UserAccountManager::$successCode){
                throw new Exception($result['message']);
            }
            if ($trans)
                Db::commit();
            return ['code'=>1,'message'=>'success','data'=>null];
        }catch (Exception $exception){
            if ($trans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage(),'data'=>null];
        }
    }
}